package com.kingzoon.seckill.base.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.kingzoon.seckill.base.Constants;


/**
 * 恶意请求拦截器
 * @author raymond
 *
 */
public class MaliciousRequestInterceptor extends BaseInterceptor {
	
	private Boolean allRequest = false;//拦截所有请求，否则拦截相同的请求
	private long minRequestIntervalTime;//允许的最小请求间隔
	private Integer maxMaliciousTimes; //允许的最大恶意请求次数

	public void setAllRequest(Boolean allRequest) {
		this.allRequest = allRequest;
	}

	public void setMinRequestIntervalTime(long minRequestIntervalTime) {
		this.minRequestIntervalTime = minRequestIntervalTime;
	}

	public void setMaxMaliciousTimes(Integer maxMaliciousTimes) {
		this.maxMaliciousTimes = maxMaliciousTimes;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HttpSession session = request.getSession();
		String preRequest = (String) session.getAttribute(Constants.PREREQUEST);
		String preRequestTime = (String) session.getAttribute(Constants.PREREQUEST_TIME);
		String url = request.getServletPath();
		if(preRequestTime != null && preRequest != null){
			if((url.equals(preRequest)|| allRequest)
					&& System.currentTimeMillis() - Long.valueOf(preRequestTime) < minRequestIntervalTime){
				Integer maliciousRequestTime = (Integer) session.getAttribute(Constants.MALICIOUS_REQUEST_TIMES);
				if(maliciousRequestTime ==null){
					maliciousRequestTime = 1;
				}else{
					maliciousRequestTime++;
				}
				session.setAttribute(Constants.MALICIOUS_REQUEST_TIMES, maliciousRequestTime);
				if(maliciousRequestTime > maxMaliciousTimes){
					response.setStatus(200);
					return false;
				}
			}else{
				session.setAttribute(Constants.MALICIOUS_REQUEST_TIMES, 0);
			}
		}
		session.setAttribute(Constants.PREREQUEST, url);
		session.setAttribute(Constants.PREREQUEST_TIME, String.valueOf(System.currentTimeMillis()));
		return super.preHandle(request, response, handler);
	}

}
